let {Sequelize,Op,DataTypes, where}=require('sequelize')

let sequelize=new Sequelize('soft','postgres','253946123',{
    host:'120.25.124.34',
    dialect:'postgres'
})

let sql = sequelize.define('blogs',{
    headline:{
        type:DataTypes.STRING,
    },
    abstract:{
        type:DataTypes.STRING
    },
    content:{
        type:DataTypes.STRING
    },
    classify:{
        type:DataTypes.STRING
    },
    author:{
        type:DataTypes.STRING
    }
})

// sequelize.sync({force:true})
async function sync()
{
   await sequelize.sync({'force':true})
    sql.bulkCreate([
        {
            headline:'论EF core的自我修养',
            abstract:'论EF core的自我修养',
            content:'论EF core的自我修养',
            classify:'.Net',
            author:'InCerry'
        },
        {
            headline:'DD之我见',
            abstract:'DD之我见',
            content:'DD之我见',
            classify:'编程技术',
            author:'某大神'
        },
        {
            headline:'nginx负载平衡的几种策略',
            abstract:'nginx负载平衡的几种策略',
            content:'nginx负载平衡的几种策略',
            classify:'服务器',
            author:'老胡来也'
        },
        {
            headline:'Linux用户创建的学习研究',
            abstract:'Linux用户创建的学习研究',
            content:'Linux用户创建的学习研究',
            classify:'Linux',
            author:'某大神'
        }, 
        {
            headline:'大数据仪表盘探讨',
            abstract:'大数据仪表盘探讨',
            content:'大数据仪表盘探讨',
            classify:'大数据',
            author:'居家八十'
        }
    ])
}

sync()


let koa=require('koa')
let app = new koa()

let Router=require('koa-router')
let router = new Router()

let bodyparser= require('koa-bodyparser')()
let cors= require('koa-cors')()

router.get('/user',async function(ctx)
{
    let id=ctx.request.query.id
    if(id)
    {
        ctx.body=await sql.findAll({
            where:{
                [Op.or]:[
                    {id:isNaN(id)?0:parseInt(id)},
                    {headline:id},
                    {abstract:id},
                    {content:id},
                    {classify:id},
                    {author:id},
                ]
            }
        },{
                order:['id']
        })
    }else
    {
        ctx.body=await sql.findAll({
            order:['id']
        })
    }
    
})

router.delete('/delete/:id',async function(ctx)
{
    let id = ctx.request.params.id
    await sql.destroy({
        where:{
            id:id
        }
    })
    ctx.body= await sql.findAll()
})

router.post('/post',async function(ctx)
{
    let obj = ctx.request.body
    await sql.create(obj)
    ctx.body= await sql.findAll()
})
router.put('/put',async function(ctx)
{
    let obj = ctx.request.body
    await sql.update(obj,{
        where:{
            id:obj.id
        }
    })
    ctx.body= await sql.findAll()
})
app.use(cors)
app.use(bodyparser)
app.use(router.routes())

app.listen(8000)